"""Text parsing utilities for extracting tasks from formatted text."""

import re
from typing import List, Tuple
from .models import TaskStatus


class TaskParser:
    """Parses formatted text to extract task information."""
    
    def __init__(self):
        # Regex patterns for task parsing
        self.task_patterns = [
            # Pattern for tasks with checkboxes: ☒ or ☐ followed by optional task ID and task name
            r'^\s*[⎿]*\s*[☒☐]\s*(?:TASK-\d+:\s*)?(.*?)\s*(?:-\s*(?:COMPLETED|SKIPPED|TODO)\s*[✅]?)?$',
            # Pattern for tasks without checkboxes but with TASK- prefix
            r'^\s*[⎿]*\s*(?:TASK-\d+:\s*)?(.*?)(?:\s*-\s*(?:COMPLETED|SKIPPED|TODO)\s*[✅]?)?$',
            # Pattern for simple task names (fallback)
            r'^\s*[⎿]*\s*(.*?)\s*$'
        ]
        
        # Status detection patterns
        self.completed_pattern = r'☒|COMPLETED\s*✅?'
        self.skipped_pattern = r'SKIPPED'
        self.todo_pattern = r'☐|TODO'
    
    def parse_task_line(self, line: str) -> Tuple[str, TaskStatus]:
        """Parse a single line to extract task name and status."""
        line = line.strip()
        
        if not line:
            return None, None
        
        # Determine status first
        status = TaskStatus.TODO  # default
        
        if re.search(self.skipped_pattern, line, re.IGNORECASE):
            status = TaskStatus.SKIPPED
        elif re.search(self.completed_pattern, line, re.IGNORECASE):
            status = TaskStatus.DONE
        elif re.search(self.todo_pattern, line, re.IGNORECASE):
            status = TaskStatus.TODO
        
        # Extract task name
        task_name = None
        for pattern in self.task_patterns:
            match = re.match(pattern, line, re.IGNORECASE)
            if match:
                task_name = match.group(1).strip()
                if task_name:
                    # Clean up the task name
                    task_name = self.clean_task_name(task_name)
                    break
        
        if task_name and self.is_valid_task_name(task_name):
            return task_name, status
        
        return None, None
    
    def clean_task_name(self, name: str) -> str:
        """Clean and normalize task name."""
        # Remove extra whitespace
        name = ' '.join(name.split())
        
        # Remove trailing status indicators
        name = re.sub(r'\s*-\s*(?:COMPLETED|SKIPPED|TODO)\s*[✅]?$', '', name, flags=re.IGNORECASE)
        
        # Remove leading/trailing punctuation if it's not meaningful
        name = name.strip('.,;:')
        
        return name.strip()
    
    def is_valid_task_name(self, name: str) -> bool:
        """Check if the extracted name is a valid task name."""
        if not name or len(name.strip()) < 2:
            return False
        
        # Skip lines that are just status indicators
        if re.match(r'^(?:COMPLETED|SKIPPED|TODO|DONE)$', name.strip(), re.IGNORECASE):
            return False
        
        # Skip lines that are just symbols or numbers
        if re.match(r'^[⎿☒☐✅\-\s\d]*$', name):
            return False
        
        return True
    
    def parse_multi_line_text(self, text: str) -> List[Tuple[str, TaskStatus]]:
        """Parse multi-line text and extract all tasks."""
        lines = text.split('\n')
        tasks = []
        
        for line in lines:
            task_name, status = self.parse_task_line(line)
            if task_name:
                tasks.append((task_name, status))
        
        return tasks
    
    def parse_comma_separated_tasks(self, text: str) -> List[str]:
        """Parse comma-separated task names."""
        tasks = []
        parts = text.split(',')
        
        for part in parts:
            task_name = part.strip()
            if task_name and len(task_name) > 1:
                tasks.append(task_name)
        
        return tasks